package cn.kduck.plugin.idea.dialog;

import cn.kduck.plugin.idea.generate.CodeGenerator;
import cn.kduck.plugin.idea.generate.impl.ConstantBasedGenerator;
import cn.kduck.plugin.idea.generate.impl.EnumBasedGenerator;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class GenerateMapBeanDialog extends DialogWrapper {

    private final Project project;
    private final PsiClass javaClass;
    private List<PsiField> fieldList = new ArrayList();
    private MapBeanForm form;

    private List<CodeGenerator> codeGeneratorList = new ArrayList<>();

    public GenerateMapBeanDialog(Project project, PsiClass javaClass) {
        super(true); // use current window as parent
        this.project = project;
        this.javaClass = javaClass;
        setTitle("转换属性");
        setResizable(false);
        setSize(300,400);
        init();

        codeGeneratorList.add(new ConstantBasedGenerator());
        codeGeneratorList.add(new EnumBasedGenerator());
    }

    public void addField(PsiField field){
        form.addField(field.getName()+":"+field.getType().getPresentableText());
        fieldList.add(field);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        form = new MapBeanForm(javaClass.getName());
        form.addPropertiesSelectionListener(e->{
            super.setOKActionEnabled(e.length > 0);
        });
        super.setOKActionEnabled(false);
        return form.getMainPanel();
    }

    @Override
    protected void doOKAction() {
        PsiField[] selectFields = getSelectFields();

        if(selectFields.length == 0){
            return;
        }

        WriteCommandAction.runWriteCommandAction(project,()->{
            for (CodeGenerator codeGenerator : codeGeneratorList) {
                if(form.getType().equals(codeGenerator.code())){
                    codeGenerator.updateCode(project,javaClass,selectFields);
                    super.doOKAction();
                    return;
                }
            }
            Messages.showErrorDialog(project, "没有合适的代码生成器实现，请更换生成模式后再试。", "错误");
        });
    }

    public void selectAll(){
        form.selectAll();
    }

    public PsiField[] getSelectFields(){
        int[] selectedIndices = form.getSelectedIndices();
        PsiField[] psiFields = new PsiField[selectedIndices.length];
        int index = 0;
        for (int selectedIndex : selectedIndices) {
            psiFields[index] = fieldList.get(selectedIndex);
            index++;
        }
        return psiFields;
    }
}
